/*
 * @Author: Jimmy
 * @LastModifiedBy: Jimmy
 * @Date: 2024-12-14 18:27:22
 * @LastEditTime: 2025-02-26 21:09:42
 * @FilePath: /monitor_belt/src/views/setting/camera/index.tsx
 */
import { remoteCameraInfo, removeDeviceById, updateCameraInfo } from "@/api/system";
import { useStore } from "@/store/conveyor";
import {
  Button,
  Card,
  Col,
  Divider,
  Flex,
  Form,
  Input,
  message,
  Row,
  Select,
  Spin,
} from "antd";
import { useEffect, useState } from "react";
import { CloseOutlined } from "@ant-design/icons";

const layout = {
  labelCol: { span: 8 },
  wrapperCol: { span: 16 },
};

const CameraConfig = () => {
  const basic_device = {
    conveyor_id: undefined,
    camera_ip: "",
    camera_port: "",
    username: "",
    password: "",
    protocol: undefined,
    device: "",
  };
  const [form] = Form.useForm();
  const { conveyorList } = useStore();
  const [loading, setLoading] = useState<boolean>(false);

  useEffect(() => {
    searchInfo();
  }, []);

  const searchInfo = async () => {
    setLoading(true);
    try {
      let res = await remoteCameraInfo();
      let { data } = res;
      form.setFieldValue("items",[...data ]);
    } finally {
      setLoading(false);
    }
  };

  const onFinish = () => {
    form
      .validateFields()
      .then(async (values) => {
        setLoading(true);
        try {
          let items = [...values.items];
          items.map(item=>{
            let findConveyor = conveyorList.find(con=>con.id==item.conveyor_id);
            item.device = findConveyor.conveyor
          })
          await updateCameraInfo(items);
          message.success("操作成功");
        } finally {
          setLoading(false);
        }
      })
      .catch((info) => {
        console.log("Validate Failed - ", info);
      });
  };

  const onReset = () => {
    form.resetFields();
  };
  return (
    <Flex flex={1} justify="center">
        <Form
          {...layout}
          form={form}
          name="basic"
          style={{ width: "1000px" }}
          onFinish={onFinish}
          initialValues={{ items: [{ ...basic_device }] }}
        >
          <Form.List name={"items"}>
            {(fields, { add, remove }) => (
              <Flex vertical gap={20}>
                {fields.map((field, index: number) => (
                  <Card
                    size="small"
                    title={`设备配置`}
                    key={field.key}
                    extra={
                      <CloseOutlined
                        onClick={async() => {
                          let {key} = field;
                          let items = form.getFieldValue('items');
                          let item = items[key]
                          if(item && item.id){
                            try{
                              setLoading(true)
                              await removeDeviceById(item.id)
                              remove(field.name);
                            }finally{
                              setLoading(false)
                            }
                          }else{
                            remove(field.name);
                          }
                        }}
                      />
                    }
                  >
                    <Row>
                      <Col span={12}>
                        <Form.Item
                          label="输送带"
                          name={[field.name, "conveyor_id"]}
                          rules={[{ required: true }]}
                        >
                          <Select
                            allowClear
                            placeholder="请选择运输线"
                            style={{ width: "100%" }}
                            fieldNames={{ label: "conveyor", value: "id" }}
                            options={[...conveyorList]}
                          />
                        </Form.Item>
                      </Col>
                      <Col span={12}>
                        <Form.Item
                          label="相机IP"
                          name={[field.name, "camera_ip"]}
                          rules={[{ required: true }]}
                        >
                          <Input placeholder="请输入相机IP" />
                        </Form.Item>
                      </Col>
                      <Col span={12}>
                        <Form.Item
                          label="相机端口"
                          name={[field.name, "camera_port"]}
                          rules={[{ required: true }]}
                        >
                          <Input placeholder="请输入相机端口" />
                        </Form.Item>
                      </Col>
                      <Col span={12}>
                        <Form.Item
                          label="协议"
                          name={[field.name, "protocol"]}
                          rules={[{ required: true }]}
                        >
                          <Select
                            allowClear
                            placeholder="请选择协议"
                            style={{ width: "100%" }}
                            options={[
                              { label: "GB28181", value: "GB28181" },
                              { label: "RTSP", value: "RTSP" },
                            ]}
                          />
                        </Form.Item>
                      </Col>
                      <Col span={12}>
                        <Form.Item
                          label="用户名"
                          name={[field.name, "username"]}
                          rules={[{ required: true }]}
                        >
                          <Input placeholder="请输入用户名" />
                        </Form.Item>
                      </Col>
                      <Col span={12}>
                        <Form.Item
                          label="密码"
                          name={[field.name, "password"]}
                          rules={[{ required: true }]}
                        >
                          <Input placeholder="请输入密码" />
                        </Form.Item>
                      </Col>
                    </Row>
                    <Divider />
                  </Card>
                ))}
                <Button
                  type="dashed"
                  size="large"
                  style={{ width: "240px", margin: "0 auto" }}
                  onClick={() => add()}
                  block
                >
                  添加设备配置
                </Button>
              </Flex>
            )}
          </Form.List>
          <Flex gap={20} justify="center" style={{ marginTop: "20px" }}>
            <Button htmlType="button" onClick={onReset}>
              重置
            </Button>
            <Button type="primary" htmlType="submit">
              保存
            </Button>
          </Flex>
        </Form>
        <Spin spinning={loading} fullscreen />
    </Flex>
  );
};

export default CameraConfig;
